package com.hu.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hu.pojo.PublicPeriod;
import com.hu.pojo.Result;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @功能：
 * @版本： V1
 * @版权： 信息技术有限公司（http://www.mychery.com/）
 * @作者： 磐石战队开发组  00355760
 * @日期： 2024/10/22 13:57
 */

public class PeriodAdjuster {
    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static Result adjustPeriods(Result result, Req req) {
        List<String> titles = new ArrayList<>(result.getTitles());
        List<PublicPeriod> periods = new ArrayList<>(result.getPeriods());

        LocalDateTime currentDate = LocalDateTime.parse(periods.get(periods.size() - 1).getEnd(), DateTimeFormatter.ofPattern(DATE_PATTERN));
        int nDays = getDays(periods.get(periods.size() - 1));

        Date endofDate = Date.from(currentDate.toLocalDate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
        List<PublicPeriod> newPeriods = new ArrayList<>();

        for (int i = 0; i < periods.size(); i++) {
            PublicPeriod period = periods.get(i);
            LocalDateTime start = LocalDateTime.parse(period.getStart(), DateTimeFormatter.ofPattern(DATE_PATTERN));
            LocalDateTime originalEnd = LocalDateTime.parse(period.getEnd(), DateTimeFormatter.ofPattern(DATE_PATTERN));
            LocalDateTime end = start;

            if ("year".equals(req.getPeriodType())) {
                if (ObjectUtil.equal(currentDate.toLocalDate(), DateUtil.endOfMonth(endofDate).toLocalDateTime().toLocalDate())) {
                    if (i == periods.size() - 1) {
                        end = currentDate;
                    } else {
                        end = DateUtil.endOfMonth(Date.from(start.toLocalDate().plusMonths(endofDate.getMonth()).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())).toLocalDateTime();
                    }
                }
                else {
                    if (i == periods.size() - 1) {
                        end = currentDate;
                    } else {
                        end = DateUtil.beginOfMonth
                                        (Date.from(start.toLocalDate().plusMonths(endofDate.getMonth()).atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()))
                                .toLocalDateTime().plusDays(currentDate.getDayOfMonth()-1).withHour(23).withMinute(59).withSecond(59);
                    }
                }
            } else if ("quarter".equals(req.getPeriodType())) {
                int monthValue = currentDate.toLocalDate().getMonthValue();
                if (ObjectUtil.equal(monthValue%3,0) && currentDate.toLocalDate().equals(currentDate.toLocalDate().withDayOfMonth(currentDate.toLocalDate().lengthOfMonth()))){
                    end = originalEnd;
                } else {
                    end = end.plusDays(nDays).withHour(23).withMinute(59).withSecond(59);
                }
            } else if ("month".equals(req.getPeriodType())) {
                if (currentDate.getMonthValue() != 2) {
                    if (ObjectUtil.equal(currentDate.toLocalDate(), DateUtil.endOfMonth(endofDate).toLocalDateTime().toLocalDate())) {
                        end = DateUtil.endOfMonth(Date.from(end.toLocalDate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())).toLocalDateTime();
                    } else {
                        if (ObjectUtil.equal(nDays, DateUtil.endOfMonth(Date.from(end.toLocalDate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())).dayOfMonth())) {
                            end = DateUtil.endOfMonth(Date.from(end.toLocalDate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())).toLocalDateTime();
                        } else {
                            end = end.plusDays(Math.min(nDays, DateUtil.endOfMonth(endofDate).dayOfMonth()));
                        }
                    }
                } else {
                    if (ObjectUtil.equal(currentDate.toLocalDate(), DateUtil.endOfMonth(endofDate).toLocalDateTime().toLocalDate())) {
                        end = DateUtil.endOfMonth(Date.from(end.toLocalDate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant())).toLocalDateTime();
                    } else {
                        end = end.plusDays(nDays);
                    }
                }
            } else if ("week".equals(req.getPeriodType())) {
                int dayOfWeekDifference = end.plusDays(nDays).getDayOfWeek().getValue() - start.getDayOfWeek().getValue();
                if (dayOfWeekDifference < 0) {
                    dayOfWeekDifference += 7;
                }
                end = end.plusDays(dayOfWeekDifference);
            }
            newPeriods.add(new PublicPeriod(start.format(DateTimeFormatter.ofPattern(DATE_PATTERN)), end.format(DateTimeFormatter.ofPattern(DATE_PATTERN))));
        }
        return new Result(titles, newPeriods);
    }

    private static int getDays(PublicPeriod lastPeriod) {
        LocalDate lastPeriodStart = LocalDate.parse(lastPeriod.getStart(), DateTimeFormatter.ofPattern(DATE_PATTERN));
        LocalDate lastPeriodEnd = LocalDate.parse(lastPeriod.getEnd(), DateTimeFormatter.ofPattern(DATE_PATTERN));
        return (int) lastPeriodEnd.toEpochDay() - (int) lastPeriodStart.toEpochDay();
    }

    public static void main(String[] args) {
        // 示例数据
        Result result1 = new Result();
        List<String> titles = new ArrayList<>();
        titles.add(new String("2019"));
        titles.add(new String("2020"));
        titles.add(new String("2021"));
        titles.add(new String("2022"));
        titles.add(new String("2023"));
        titles.add(new String("2024"));
        List<PublicPeriod> result = new ArrayList<>();
        // result.add(new PublicPeriod("2019-01-01 00:00:00", "2019-12-31 23:59:59"));
        // result.add(new PublicPeriod("2020-01-01 00:00:00", "2020-12-31 23:59:59"));
        // result.add(new PublicPeriod("2021-01-01 00:00:00", "2021-12-31 23:59:59"));
        // result.add(new PublicPeriod("2022-01-01 00:00:00", "2022-12-31 23:59:59"));
        // result.add(new PublicPeriod("2023-01-01 00:00:00", "2023-12-31 23:59:59"));
        // result.add(new PublicPeriod("2024-02-01 00:00:00", "2024-10-15 23:59:59"));

        result.add(new PublicPeriod("2023-07-01 00:00:00", "2023-09-30 23:59:59"));
        result.add(new PublicPeriod("2023-10-01 00:00:00", "2023-12-31 23:59:59"));
        result.add(new PublicPeriod("2024-01-01 00:00:00", "2024-03-31 23:59:59"));
        result.add(new PublicPeriod("2024-04-01 00:00:00", "2024-06-30 23:59:59"));
        result.add(new PublicPeriod("2024-07-01 00:00:00", "2024-09-30 23:59:59"));
        result.add(new PublicPeriod("2024-10-01 00:00:00", "2024-12-30 23:59:59")); //如果是本季度末，前面的都取季度末

        result1.setPeriods(result);
        result1.setTitles(titles);
        // Result result = TimeToChineseUtil.generateQuarterPeriods(2024, 4,7);
        // Result result = TimeToChineseUtil.generateYearPeriods(2024, 7);
        System.out.println(result);
        Req req = new Req("quarter", "2024", "4");

        Result newResult = adjustPeriods(result1, req);

        System.out.println(newResult);

    }
}


class Req {
    private String periodType;
    private String year;
    private String periodValue;

    public Req(String periodType, String year, String periodValue) {
        this.periodType = periodType;
        this.year = year;
        this.periodValue = periodValue;
    }

    public String getPeriodType() {
        return periodType;
    }

    public void setPeriodType(String periodType) {
        this.periodType = periodType;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getPeriodValue() {
        return periodValue;
    }

    public void setPeriodValue(String periodValue) {
        this.periodValue = periodValue;
    }
}

